/*************************************************************************
 *
 * SerialTask
 * 
 * (c) Ales Povalac, alpov@alpov.net, http://www.alpov.net/
 * 
 *************************************************************************
 *
 * $Id: serial.c 119 2007-01-22 17:35:57Z Ales $
 * 
 *************************************************************************/         

#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <avr/pgmspace.h>
#include "../avrx/avrx.h"
#include "../avrx/AvrXFifo.h"
#include "hw.h"
#include "serial.h"
#include "serial_hnds.h"
#include "data.h"
#include "sensor.h"

#include "../global/serial.c"


/*************************************************************************
 * odeslani udaju typu RWDATA na zadanou adresu 
 *************************************************************************/ 
void Serial_RWDATA_W(unsigned char item, unsigned char addr)
{
    PACKET_HEADER ph;
    TimerControlBlock timer;
    
    timer.semaphore = SEM_PEND;
    
    ph.src = addr; // handler -> dest=src
    ph.item_hi = item;
    ph.item_lo = 0;
    
    if (addr == ADDR_BROADCAST) {
        RWDATA_R_Handler(&ph, NULL, 0);
    } else {
        for (int i = 0; i < PACKET_TX_TRIES; i++) {
            RWDATA_R_Handler(&ph, NULL, 0);
            if (SerialWaitAck(ph.seq))
                return;
            AvrXDelay(&timer, PACKET_RAND_DELAY);
        }
        // fixme: obsluha chyby
    }
}


/*************************************************************************
 * odeslani udaju typu STDATA na broadcast 
 *************************************************************************/ 
void Serial_STDATA_W(unsigned char item)
{
    PACKET_HEADER ph;
    
    ph.src = ADDR_BROADCAST; // handler -> dest=src
    ph.item_hi = item;
    ph.item_lo = 0;
    
    STDATA_R_Handler(&ph, NULL, 0);
}

